package com.latefly.skewwork.network.okhttp3

import android.os.Environment
import okhttp3.Call
import okhttp3.Callback
import okhttp3.FormBody
import okhttp3.MediaType.Companion.toMediaType
import okhttp3.MultipartBody
import okhttp3.OkHttpClient
import okhttp3.Request
import okhttp3.RequestBody
import okhttp3.RequestBody.Companion.asRequestBody
import okhttp3.Response
import okio.IOException
import java.io.File
import java.io.FileOutputStream

class OkHttp {
    private fun asyncGet() {
        val url = ""
        //创建request请求对象
        val request = Request.Builder()
            .url(url)
            //.method()方法与.get()方法选取1种即可
            .method("GET", null)
            .build()

        //创建call并调用enqueue()方法实现网络请求
        OkHttpClient().newCall(request)
            .enqueue(object : Callback {
                override fun onFailure(call: Call, e: IOException) {
                }

                override fun onResponse(call: Call, response: Response) {
                }
            })
    }

    private fun asyncPost() {
        val url = ""
        //添加post请求参数
        val requestBody = FormBody.Builder()
            .add("userName", "name")
            .add("passWord", "pass")
            .build()

        //创建request请求对象
        val request = Request.Builder()
            .url(url)
            .post(requestBody)
            .build()

        //创建call并调用enqueue()方法实现网络请求
        OkHttpClient().newCall(request)
            .enqueue(object : Callback {
                override fun onFailure(call: Call, e: IOException) {
                }

                override fun onResponse(call: Call, response: Response) {
                }
            })
    }

    private fun asyncUploadFile() {
        val url = ""
        //创建file
        val filePath = Environment.getExternalStorageDirectory().absolutePath
        val file = File(filePath, "test.txt")

        //创建request请求对象
        val request = Request.Builder()
            .url(url)
            .post(file.asRequestBody("text/txt; charset=utf-8".toMediaType()))
            .build()

        //创建call并调用enqueue()方法实现网络请求
        OkHttpClient().newCall(request)
            .enqueue(object : Callback {
                override fun onFailure(call: Call, e: IOException) {
                }

                override fun onResponse(call: Call, response: Response) {
                }
            })
    }

    private fun asyncDownloadFile() {
        val url = ""
        //创建request请求对象
        val request = Request.Builder()
            .url(url)
            .build()

        //创建call并调用enqueue()方法实现网络请求
        OkHttpClient().newCall(request)
            .enqueue(object : Callback {
                override fun onFailure(call: Call, e: IOException) {
                }

                override fun onResponse(call: Call, response: Response) {
                    //响应成功后，从response获取输入流，写入到文件中
                    val inputStream = response.body!!.byteStream()
                    val filePath = Environment.getExternalStorageDirectory().absolutePath
                    val file = File(filePath, "test.txt")
                    val fileOutputStream = FileOutputStream(file)
                    val buffer = ByteArray(2048)
                    do {
                        val len = inputStream.read(buffer)
                        fileOutputStream.write(buffer, 0, len)
                    } while (len != -1)
                    fileOutputStream.flush()
                }
            })
    }

    private fun asyncUploadMultipart() {
        val url = ""
        //创建MultipartBody
        val requestBody = MultipartBody.Builder()
            .setType(MultipartBody.FORM)
            .addFormDataPart("title", "img")
            .addFormDataPart(
                "image",
                "test.png",
                RequestBody.create("image/png".toMediaType(), File("/sdcard/test.png"))
            )
            .build()

        //创建request请求对象
        val request = Request.Builder()
            .url(url)
            .post(requestBody)
            .build()

        //创建call并调用enqueue()方法实现网络请求
        OkHttpClient().newCall(request)
            .enqueue(object : Callback {
                override fun onFailure(call: Call, e: IOException) {
                }

                override fun onResponse(call: Call, response: Response) {
                }
            })

    }
    //设置超时时间和缓存
//    private fun setTimeoutAndCache() {
//        val cacheDir=externalCacheDir
//        val cacheSize=10*1024*1024L
//        val okHttpClientBuilder=OkHttpClient.Builder()
//            .connectTimeout(20, TimeUnit.SECONDS)
//            .readTimeout(20,TimeUnit.SECONDS)
//            .writeTimeout(20,TimeUnit.SECONDS)
//            .cache(Cache(File(cacheDir,"cache.txt"),cacheSize))
//        val okHttpClient=okHttpClientBuilder.build()
//    }

}